#include "KSocketIocp.h"
#include "KGlobal.h"
#include "KSocket.h"

KSocketIocp::KSocketIocp(DWORD threads)
{
    m_iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, threads);
}

KSocketIocp::~KSocketIocp()
{
    if (m_iocp) {
        CloseHandle(m_iocp);
    }
}

BOOL KSocketIocp::addSocket(KSocket *sock, ULONG_PTR key)
{
    assert(sock != NULL && m_iocp != NULL);
    return CreateIoCompletionPort(reinterpret_cast<HANDLE>(sock->handle()), m_iocp, key, 0) == m_iocp;
}

BOOL KSocketIocp::getStatus(LPDWORD lpBytes, PULONG_PTR lpKey, LPOVERLAPPED *lpOverlapped, DWORD ms)
{
    assert(m_iocp != NULL);
    return GetQueuedCompletionStatus(m_iocp, lpBytes, lpKey, lpOverlapped, ms);
}

BOOL KSocketIocp::getStatus(Status &status, DWORD ms)
{
    assert(m_iocp != NULL);
    return GetQueuedCompletionStatus(m_iocp, &status.bytes, &status.key, &status.lpOvlp, ms);
}

BOOL KSocketIocp::postStatus(const Status &status)
{
    assert(m_iocp != NULL);
    return PostQueuedCompletionStatus(m_iocp, status.bytes, status.key, status.lpOvlp);
}